#include "groundlayer.h"
#include <math.h>
#include <QByteArray>
#include <QDataStream>
#include <QTimer>
#include <QDebug>

groundLayer::groundLayer(QString layerName, double hBottom, double hTop,
			 QObject *parent) :
	AtmosLayer(layerName, hBottom, hTop, parent),
	m_groundAlbedo(0.3)
{
	connect(this, SIGNAL(groundScatUp(QByteArray)),
		this, SLOT(recvScatInUp(QByteArray)));

	//caculation procedure for Lamb-ground-approximation,
	//caculate downard irridiance, then the up-intensity is got.
	//Must change procedure for BRDF or PBRDF model!!!
	connect(this, SIGNAL(gotDownIrradiance(double)),
		this, SLOT(recvDownIrridance()));
}


void groundLayer::recvDownIrridance()
{
	QTimer::singleShot(10, this, SLOT(groundScatResponse()));
}

//caculation procedure for Lamb-ground-approximation,
//caculate downard irridiance, then the up-intensity is got.
//BRDF mode is not realized, 2011-11-4
#include <stdio.h>
void groundLayer::groundScatResponse()
{
	qDebug() << "groundLayer::groundScatResponse(). m_currentIrradiance/m_downIrradiance: " << m_currentIrradiance/m_downIrradiance;
	if(m_currentIrradiance < m_downIrradiance*0.0001){
		qDebug() << "Interate caculation over, current step's down irradiance at ground is:" << m_currentIrradiance <<"\n\n\n*************************************\n\n\n\n";
		printf("\a");
		exit(0);
	}

	//change directon
	m_currentDir = UP;

	double intensity = m_currentIrradiance * m_groundAlbedo;

//	double groundScatLight[N_PI/2][N_PI*2][3];
	QByteArray light;
	QDataStream strm(&light, QIODevice::ReadWrite);
	for(int i = 0; i < N_PI/2; i++){
		for(int j = 0; j < N_PI * 2; j++){
			strm << intensity
			     << (double) 0.0 << (double) 0.0;
//			qDebug() << "groundScatResponse()"
//				 << i << j << intensity << m_currentIrridiance;
		}
	}

	emit(groundScatUp(light));
}

void groundLayer::setGroundAlbedo(double albedo)
{
	m_groundAlbedo = albedo;
}

double groundLayer::getCurrentGroundAlbedo()
{
	return m_groundAlbedo;
}
